package com.source.module_ipc_client;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import com.source.module_ipc_client.base.Constant;
import com.source.module_ipc_server.IProcessInfo;

/**
 * @author Created by wsl
 * @des 客户端首页
 * @date 2022/6/9
 */
public class IPCClientMainActivity extends AppCompatActivity implements View.OnClickListener {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ipc_client_main);

        findViewById(R.id.btn_bind_remote).setOnClickListener(this);
        findViewById(R.id.btn_unbind_remote).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_bind_remote) {
            bindRemoteService();
        } else if (id == R.id.btn_unbind_remote) {
            unbindService(mServerServiceConnection);
        }
    }

    // 绑定远程服务
    public void bindRemoteService() {
        Intent intent = new Intent();
        intent.setAction("com.source.module_ipc_server.service.IPCRemoteService");//Service的action
        intent.setPackage("com.example.my");//App A的包名
        bindService(intent, mServerServiceConnection, BIND_AUTO_CREATE);
    }


    ServiceConnection mServerServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            Log.e(Constant.TAG, "MyRemoteService onServiceConnected");
            // 通过aidl取出数据
            IProcessInfo processInfo = IProcessInfo.Stub.asInterface(service);
            try {
                Log.e(Constant.TAG, "MyRemoteService process id = " + processInfo.getProcessId());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(Constant.TAG, "MyRemoteService onServiceDisconnected");
        }
    };

}
